<!-- 抓包规则配置 -->
<template>
  <div class="container">
    <!-- 搜索表单 -->
    <yd-form :options="formOptions" :model="formData" :btns="formBtns"></yd-form>

    <!--查询列表-->
    <YdTable
      :formData="formData"
      :tableConfig="tableConfig"
      :tableData="tableData"
      ref="multipleTable"
      @sizeChangeHandler="queryProbeDataFilter"
      @currentChangeHandler="queryProbeDataFilter"
      @sortChangeHandler="queryProbeDataFilter"
      @selectionChangeHandler="handleSelectionChange"
    >
    </YdTable>

    <!-- 新增修改探针过滤对话框 -->
    <el-dialog :title="title" v-model="open"  width="800px" append-to-body center>
      <el-form ref="pacForm" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="120px" label="探针服务器IP" prop="probeServerIp">
              <el-input v-model="form.probeServerIp"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="120px" label="过滤规则名称" prop="name">
              <el-input maxlength="30" v-model="form.name"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" label-width="120px" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                :disabled-date="disabledDate"
                placeholder="最早三分钟以后"
                v-bind:default-time="defaultTime"
                v-bind:default-value="defaultValue"
                @change="handleChangeDate"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="120px" label="执行时间" prop="timeCountdown">
              <el-select v-model="form.timeCountdown" @change="$forceUpdate()" clearable placeholder="请选择">
                <el-option
                  v-for="item in options.timeCountdownOption"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="120px" label="关键字" prop="keyword">
              <el-input maxlength="50" v-model="form.keyword"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="120px" label="会话模式" prop="sessionModel">
              <el-select v-model="form.sessionModel" @change="$forceUpdate()" clearable placeholder="请选择">
                <el-option
                  v-for="item in options.sessionModelOption"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label-width="120px" label="保留IP表达式" prop="ipSaveSet" style="width: 100%;">
            <el-input placeholder="(10.1.1.120-10.1.1.110|123.1.1.4-172.1.1.1|124.0.0.1-224.5.5.5)" v-model="form.ipSaveSet"/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label-width="120px" label="屏蔽IP表达式" prop="ipDropSet" style="width: 100%;">
            <el-input placeholder="10.1.1.128|176.3.3.3" v-model="form.ipDropSet"/>
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button type="primary" :loading="commitLoading" @click="submitForm">确 定</el-button>
        <el-button :loading="commitLoading" @click="cancelHandle">取 消</el-button>
      </template>
    </el-dialog>
    <el-dialog title="提示" v-model="sendOpen" width="400px" append-to-body >
      <span v-if="sendType">发送过滤规则,等待探针返回处理结果...!</span>
      <span v-if="!sendType">停止抓包,等待探针返回处理结果...!</span>
      <template #footer class="dialog-footer">
        <el-button type="primary" @click="closeSendOpen">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PacketCaptureRules" lang="tsx">
import {
  getProbeDataFilter, getProbeDataFilterById, addProbeDataFilter, updateProbeDataFilter,
  delProbeDataFilter, startSynFilterData, stop
} from '@/api/management/packagesAnalysis/packetCaptureRules';
import { formatDate, parseTime} from '@/utils/common';
import { ref, reactive, toRefs, onMounted } from 'vue';
import useCurrentInstance from '@/utils/useCurrentInstance';

const { proxy } = useCurrentInstance();

//校验探针服务器IP
let checkProbeServerIp = (rule: any, value: any, callback: any) => {
  if (!value || value === '' || value.trim() === '') {
    callback(new Error('探针服务器IP不能为空'))
  }
  setTimeout(() => {
    let regex = /(^\s+?.+)|(.+\s+?$)/g;
    if (regex.test(value)) {
      callback(new Error('探针服务器IP首尾不能有空格'));
    }
    if (/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/g.test(value)) {
      if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256)
        callback();
    } else {
      callback(new Error('ip格式不符合规范'));
    }
  }, 1000)
};
//校验关键字
let checkKeyword = (rule: any, value: any, callback: any) => {
  if (form.value.sessionModel === 1 && (!value || value.trim() === '')) {
    callback(new Error('会话模式下,关键字不允许为空'));
  } else {
    callback();
  }
};
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 弹出层标题
const title = ref("");
const open = ref(false);
//发送规则提示层
const sendOpen = ref(false);
//发送规则类型 true抓包 false停止
const sendType = ref(true);
//下拉框选项
let options = reactive({
  filterStatusOptions: [
    {
      value: 0,
      label: '未过滤',
    }, {
      value: 2,
      label: '已同步',
    }],
  timeCountdownOption: [
    {
      key: 10,
      value: '10s',
    }, {
      key: 20,
      value: '20s',
    }, {
      key: 30,
      value: '30s',
    }, {
      key: 60,
      value: '1min',
    }, {
      key: 180,
      value: '3min',
    }, {
      key: 300,
      value: '5min',
    }],
  sessionModelOption: [
    {
      key: 0,
      value: '否',
    }, {
      key: 1,
      value: '是',
    }]
});
const formOptions = reactive < FormOptionType > ([
  {
    type: 'select',
    label: '过滤状态',
    prop: 'filterStatus',
    selectKey: 'value',
    isInitValue: false,
    children: options.filterStatusOptions,
  },
  {
    type: 'input',
    label: '探针服务器IP',
    prop: 'probeServerIp',
    attrs: {
      clearable: true,
    },
  },
]);
const formBtns = reactive<BtnType[]> ([
  {
    type: 'primary',
    text: '查询',
    handler: searchProbeDataFilterHandler,
  },
]);
// 表单参数
const data = reactive<anyObj>({
  form: {}
});
const { form } = toRefs(data);
let addDialogForm = reactive({
  // 是否显示弹出层
  open: false,
  //是否显示确认提交按钮，查看详情的时候不需要确认按钮
  showSubmit: true,
  showClose: false,
  inputReadOnly: false
});
// 表单校验
const rules = ref({
  probeServerIp: [
    {required: true, validator: checkProbeServerIp, trigger: "blur"}
  ],
  name: [
    {required: true, message: "过滤规则名称", trigger: "blur"}
  ],
  startTime: [
    {required: true, message: "开始时间不能为空", trigger: "blur"}
  ],
  timeCountdown: [
    {required: true, message: "执行时间不能为空", trigger: "blur"}
  ],
  keyword: [
    {validator: checkKeyword, trigger: "blur"}
  ]
});
let commitLoading = ref(false);
// 搜索表单数据
let formData = reactive<anyObj>({});
//操作完返回信息
let resultData: anyObj = {};
//行消息提示类型。
const rowMsgType = ref(3);
// 列表配置
let tableConfig = reactive({
  url: getProbeDataFilter,
  columns: [
    {
      label: '过滤ID',
      prop: 'id',
      width:90
    },
    {
      label: '探针服务器IP',
      prop: 'probeServerIp',
      renderXss: (row: anyObj, value: any) => {
        if (!resultData.ids) {
          return value;
        }
        let returnValue = value;
        const ipv = resultData.ids;
        if (ipv !== undefined && ipv != null && ipv.length > 0) {
          for (let s = 0; s < ipv.length; s++) {
            if (row.id == ipv[s]) {
              if (rowMsgType.value === 1) {
                returnValue = (<span>{value}<span style='color:red'>(发送失败)</span></span>);
                return returnValue;
              } else if (rowMsgType.value === 0) {
                returnValue = (<span>{value}<span style='color:red'>(停止失败)</span></span>);
                return returnValue;
              } else {
                returnValue = (<span>{value}<span style='color:red'>(操作失败)</span></span>);
                return returnValue;
              }
            }
          }
        }
        if (resultData.sucid != null && resultData.sucid !== undefined) {
          var idv = resultData.sucid;
          for (var s = 0; s < idv.length; s++) {
            if (row.id == idv[s]) {
              if (rowMsgType.value === 1) {
                returnValue = value + "(发送成功)";
                return returnValue;
              } else if (rowMsgType.value === 0) {
                returnValue = value + "(停止成功)";
                return returnValue;
              } else {
                returnValue = value + "(操作成功)";
                return returnValue;
              }
            }
          }
        }
        if (resultData.runid != null && resultData.runid != undefined) {
          let run = resultData.runid;
          for (let s = 0; s < run.length; s++) {
            if (row.id == run[s]) {
              if (rowMsgType.value == 1) {
                returnValue = value + "(有任务在执行)";
                return returnValue;
              }
            }
          }
        }
        return returnValue;
      }
    },
    {
      label: '过滤规则名称',
      prop: 'name'
    },
    {
      label: '开始时间',
      prop: 'startTime',
      showOverFlowToolTip: true,
      formatter(row: anyObj, value: ApiVal) {
        return parseTime(value);
      }
    },
    {
      label: '执行时间(s)',
      prop: 'timeCountdown',
      showOverFlowToolTip: true,
    },
    {
      label: '关键字',
      prop: 'keyword'
    },
    {
      label: '保留IP表达式',
      prop: 'ipSaveSet'
    },
    {
      label: '屏蔽IP表达式',
      prop: 'ipDropSet'
    },
    {
      label: '会话模式',
      prop: 'sessionModel',
      formatter(row: anyObj, val: ApiVal) {
        if (val == 0) {
          return "否";
        } else if (val == 1) {
          return "是";
        } else {
          return "";
        }
      }
    },
    {
      label: '探针过滤状态',
      prop: 'filterStatus',
      formatter(row: anyObj, val: any) {
        let option = ['未过滤', '未同步', '已同步'];
        return option[val];
      }
    },
  ],
  // 工具栏
  toolBar: [
    {name: '新增', icon: 'yd-icon-plus', permi: ['metadata:caughtDataConfig:add'], handler: () => handleAdd()},
    {name: '修改', icon: 'yd-icon-edit', permi: ['metadata:caughtDataConfig:edit'], disable: 'single', handler: () => updateHandle()},
    {name: '删除', icon: 'yd-icon-delete', permi: ['metadata:caughtDataConfig:delete'], disable: 'multiple', handler: () => deleteHandle()},
    {
      name: '发送规则',
      icon: 'yd-icon-send',
      permi: ['metadata:caughtDataConfig:send'],
      disable: 'multiple',
      handler: () => startDataFilterAction()
    },
    {
      name: '停止抓包',
      icon: 'yd-icon-stop',
      permi: ['metadata:caughtDataConfig:stop'],
      disable: 'multiple',
      handler: () => stopHandle()
    },
  ],
  // 开启复选框
  enableSelection: true,
  // 开启分页
  pagination: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  // 加载层
  loading: true
});
// 列表数据
let tableData = ref([]);
const defaultTime = ref(new Date());
const defaultValue = ref(new Date(new Date().getTime() + 600 * 300));
const gridRow = ref<any>([]);
// 禁选日期
const disabledDate = (time: any) => {
  return time.getTime() <= Date.now() - 24 * 3600 * 1000;
}
const pacForm = ref<any>();

onMounted(() => {
  queryProbeDataFilter();
});

// 默认开始时间为三分钟以后的时间
function getDefaultTime() {
  var date = new Date();
  var min = date.getMinutes();
  date.setMinutes(min + 3);
  var h = date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours();
  var m = date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes();
  var s = date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds();
  defaultTime.value = new Date(date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+h+":"+m+":"+s);
}
//关闭发送规则弹出层
function closeSendOpen() {
  sendOpen.value = false;
}
/*搜索*/
function searchProbeDataFilterHandler() {
  formData.pageNum = 1;
  queryProbeDataFilter();
}
/*查询探针数据过滤信息*/
function queryProbeDataFilter() {
  tableConfig.loading = true;
  getProbeDataFilter(formData).then((res: ApiResponse) => {
    tableData.value = res.data.records;
    tableConfig.pagination.total = res.data.total;
    tableConfig.loading = false;
  });
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  title.value = "添加探针数据过滤";
  getDefaultTime();
  defaultValue.value = new Date(new Date().getTime() + 600 * 300);
  open.value = true;
}
/** 修改按钮操作 */
function updateHandle() {
  reset();
  title.value = "修改探针数据过滤";
  getProbeDataFilterById(ids.value).then(response => {
    form.value = response.data[0];
    open.value = true;
  });
}
/** 删除按钮操作 */
function deleteHandle() {
  if (ids.value == null) {
    proxy.$modal.msgWarning("请选择要删除的系统版本信息。");
    return;
  }
  proxy.$modal.confirm('是否需要删除已经勾选的数据?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    cancelButtonClass: 'confirm-rigth-cancel-button',
    type: "warning"
  }).then(() => {
    delProbeDataFilter(ids.value).then((res: ApiResponse) => {
      if (res.code === 0) {
        proxy.$modal.msgSuccess("删除成功");
        searchProbeDataFilterHandler();
      } else {
        proxy.$modal.msgWarning(res.msg);
      }
    });
  }).catch(() => {});
}
/**
 * 发送规则
 */
function startDataFilterAction() {
  const rows = gridRow.value;
  let id = "", probeIp = "";
  //时间晚于本机当前时间3分钟
  let localTime = new Date().getTime() + 5 * 1000;
  for (let i = 0; i < rows.length; i++) {
    let startTime = rows[i].startTime;
    //得到毫秒数
    let newTimeFormat = (new Date(startTime)).getTime();
    if (localTime > newTimeFormat) {
      proxy.$modal.msgError("开始同步时间已过，不能发送！");
      return false;
    }
    if (id === "") {
      id = id + rows[i].id;
    } else {
      id = id + ',' + rows[i].id;
    }
    if (probeIp === "") {
      probeIp = rows[i].probeServerIp;
    } else {
      probeIp = probeIp + ',' + rows[i].probeServerIp;
    }
  }
  proxy.$modal.confirm('确定发送吗?', "确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    cancelButtonClass: 'confirm-rigth-cancel-button',
    type: "warning"
  }).then(() => {
      // $alert('发送过滤规则,等待探针返回处理结果...!', '提示', {
      //     confirmButtonText: "确定",
      //     type: "info"
      // });
      sendType.value = true;
      sendOpen.value = true;
      startSynFilterData({ids: id, probeServerIp: probeIp}).then((res: ApiResponse) => {
        if (res.code === 0) {
          sendOpen.value = false;
          proxy.$modal.alert(res.msg, '提示', {
            confirmButtonText: "确定",
            type: "info"
          });
          resultData = res.data;
          rowMsgType.value = 1;
          queryProbeDataFilter();
        }
      });
  }).catch(() => {});
}
/**
 * 停止抓包
 */
function stopHandle() {
  proxy.$modal.confirm('确定停止吗?', "确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    cancelButtonClass: 'confirm-rigth-cancel-button',
    type: "warning"
  }).then(() => {
    // $alert('停止抓包,等待探针返回处理结果...!', '提示', {
    //     confirmButtonText: "确定",
    //     type: "info"
    // });
    sendType.value = false;
    sendOpen.value = true;
    stop(ids.value).then((res: ApiResponse) => {
      if (res.code === 0) {
        sendOpen.value = false;
        proxy.$modal.alert(res.msg, '提示', {
          confirmButtonText: "确定",
          type: "info"
        });
        resultData = res.data;
        rowMsgType.value = 0;
        queryProbeDataFilter();
      }
    });
  }).catch(() => {});
}
/**多选框选中数据*/
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: anyObj) => item.id);
  gridRow.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
/** 提交按钮 */
function submitForm() {
  commitLoading.value = true;
  pacForm.value.validate((valid: any) => {
    if (valid) {
      // 只作用于探针
      form.value.reach = 1;
      form.value.startTime =  formatDate(form.value.startTime);
      if (form.value.id) {
        updateProbeDataFilter(form.value).then((response: ApiResponse) => {
          if (response.code === 0) {
            open.value = false;
            proxy.$modal.msgSuccess("修改成功");
            commitLoading.value = false;
            searchProbeDataFilterHandler();
          }
        });
      } else {
        addProbeDataFilter(form.value).then((response: ApiResponse) => {
          if (response.code === 0) {
            open.value = false;
            proxy.$modal.msgSuccess("新增成功");
            commitLoading.value = false;
            searchProbeDataFilterHandler();
          }
        });
      }
    }
    commitLoading.value = false;
  });
}
/*取消*/
function cancelHandle() {
  open.value = false;
  proxy.$forceUpdate();
}
//
function reset() {
  form.value = {
    name: undefined
  };
  defaultValue.value = new Date(new Date().getTime() + 600 * 300);
  defaultTime.value = new Date();
  pacForm.value?.resetFields();
}
//下拉框改变
function changeHandle() {
  proxy.$forceUpdate();
}
//时间控件控制
function handleChangeDate(val: any) {
  if(val) {
    let startAt = new Date(form.value.startTime).getTime() * 1000 / 1000;
    if (startAt < (Date.now()+3*60*1000)) {
      form.value.startTime = parseTime(new Date().getTime() + 600 * 300);
    }
  }
}
</script>

<style scoped>
  .container {
    margin: 10px;
  }
</style>
